﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using TriplesGameDAL;
using TriplesGameLogic;

namespace TripleGameService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class TripleGamesService : ITripleGameService
    {
        public bool TryMakeMove(GameMove move)
        {
            Game game = TriplesGameDAO.GetGameByPlayerId(move.PlayerId);            
            char playerChar = TriplesGameDAO.GetPlayerCharByPlayerId(move.PlayerId);
            TriplesGame gameLogic = new TriplesGame(game.Matrix.ToCharArray());

            bool moveSuccess = gameLogic.TryMakeMove(playerChar, move.X1, move.Y1, move.X2, move.Y2);

            if (moveSuccess)
            {
                game.Matrix = CharArrayToString(gameLogic.Matrix);
                TriplesGameDAO.SaveGame(game);
            }
            return moveSuccess;
        }

        private string CharArrayToString(char[] matrix)
        {
            StringBuilder builder = new StringBuilder();
            foreach (char item in matrix)
            {
                builder.Append(item);
            }
            return builder.ToString();
        }

        public char[] GetGameMatrix(int playerId)
        {
            Game game = TriplesGameDAO.GetGameByPlayerId(playerId); 
            return game.Matrix.ToCharArray();
        }
        
        public int GetNewPlayerId()
        {
            Player newPlayer =TriplesGameDAO.CreatePlayer();
            return newPlayer.PlayerId;
        }

        public string GetGameMatrixState(int playerId)
        {
            Game game = TriplesGameDAO.GetGameByPlayerId(playerId);
            return game.State;
        }
    }
}
